import type { UserConfig, ConfigEnv } from 'vite';
import path from 'path';
import vue from '@vitejs/plugin-vue';
import AutoImport from 'unplugin-auto-import/vite';
import themePreprocessorPlugin from '@zougt/vite-plugin-theme-preprocessor';
import ViteComponents from 'unplugin-vue-components/vite';
import { AntDesignVueResolver } from 'unplugin-vue-components/resolvers';
import progress from 'vite-plugin-progress';

function pathResolve(dir: string) {
	return path.join(__dirname, dir);
}

// mode dev/production
function computedPlugins(mode) {
	const plugins = [
		vue(),
		// 主题相关
		(themePreprocessorPlugin as any).default({
			less: {
				// 各个主题文件的位置
				multipleScopeVars: [
					{
						scopeName: 'theme-default',
						path: path.resolve('src/styles/theme/default.less'),
					},
					{
						scopeName: 'theme-dark',
						path: path.resolve('src/styles/theme/dark.less'),
					},
				],
			},
		}),
		// 自动导入
		AutoImport({
			imports: ['vue'],
		}),
		// 打包进度
		progress(),
	];
	if (mode && mode === 'production') {
		plugins.push(
			ViteComponents({
				resolvers: [AntDesignVueResolver()],
			})
		);
	}
	return plugins;
}

export default ({ command, mode }: ConfigEnv): UserConfig => {
	return {
		optimizeDeps: {
			include: [
				'@vue/shared',
				'ant-design-vue/es/locale/zh_CN',
				'ant-design-vue/es/locale/en_US',
			],
		},
		base: './',
		build: {
			outDir: path.resolve(__dirname, 'dist'),
		},
		plugins: computedPlugins(mode),
		resolve: {
			alias: [
				{
					find: /@\//,
					replacement: pathResolve('src') + '/',
				},
				{
					find: /@components\//,
					replacement: pathResolve('src') + '/components/',
				},
				{
					find: /@views\//,
					replacement: pathResolve('src') + '/views/',
				},
				{
					find: /@widgets\//,
					replacement: pathResolve('src') + '/widgets/',
				},
				{
					find: /@plugins\//,
					replacement: pathResolve('src') + '/plugins/',
				},
			],
		},
		server: {
			port: 8080,
			proxy: {
				'/api': {
					target: 'http://172.16.152.66:30223/',
					// target: 'http://172.16.103.153:30093',
					// target: 'http://172.16.240.110:51001',
					changeOrigin: true,
					rewrite: (path) => path.replace(/^\/api/, ''),
				},
				'/contractmanager__contractmanager': {
					//  DemoSys
					// target: 'http://172.16.240.110:51001',
					//  EY合同
					// target: 'http://172.16.152.57:30310',
					// target: 'http://172.16.152.55:30061',
					//  Email
					// target: 'http://172.16.152.57:30223/',
					changeOrigin: true,
					rewrite: (path) => path.replace(/^\/api/, ''),
				},
			},
		},
		css: {
			preprocessorOptions: {
				less: {
					javascriptEnabled: true,
				},
			},
		},
	};
};
